#include "stm32f10x.h"
#include "lcd_zk.h"
#include "led.h"
#include "delay.h"
#include "drv_spi.h"
#include "drv_CC1101.h"
#include "drv_button.h"

//#define TX_MODE

int main(void)
{

#ifdef TX_MODE
    const char *msg[8] = { "awdesq", "oditsz", "thinks", "zoufeng", "fuck U ", "window", "helpme", "debugs"};
    uint8_t i = 0, count = 0;
    print_char( 0, 0, 0xFF);
    delay_init( );
    delay_ms(300);
    led_init();
    drv_spi_init( );
    CC1101_Init( );
    initial_lcd( );
    clear_screen( );
    display_GB2312_string(0, 0, (unsigned char*)"Count:" );
    display_GB2312_string(2, 0, (unsigned char*)"Addr:" );
    display_GB2312_string(4, 0, (unsigned char*)"Msg:" );
    
    while( 1 ){
        print_byte( 2, 50, i );
        display_GB2312_string(4, 50, (uint8_t *)msg[i]);
        CC1101_Tx_Packet( 0x04, 6, (uint8_t *)msg[i]);
        i = ( ++i == 8 ) ? 0 : i;
        led_on();
        while( CC1101_Read_Status( CC1101_MARCSTATE ) != STATE_IDLE );
        led_off();
        print_byte( 0, 50, ++count );
        delay_ms(500);
    }
#else
    uint8_t count = 0, status[2], pktlen, address;
    uint8_t buff[64];
    delay_init( );
    delay_ms(300);
    led_init();
    drv_spi_init( );
    CC1101_Init( );
    initial_lcd( );
    clear_screen( );    
    clear_screen();
    CC1101_Clear_RxBuffer;
    CC1101_Set_Address( 0x04 );
    CC1101_Rx_Mode;
    while( 1 )
    {
        //等待发送完成,回到IDLE模式
        while( CC1101_Read_Status( CC1101_MARCSTATE ) != STATE_IDLE );

        //打印长度
        clear_screen( );
        pktlen = CC1101_Read_Reg( CC1101_RXFIFO );
        address = CC1101_Read_Reg( CC1101_RXFIFO );
        
        display_GB2312_string( 0, 0, (unsigned char*)"Len:" );
        print_byte( 0, 50, pktlen - 1 );
        print_byte( 0, 100, address );
        
        //读取内容
        CC1101_Read_Multi_Reg( CC1101_RXFIFO, buff, pktlen -1 );
        buff[ pktlen ] = 0;
        //显示内容
        display_GB2312_string( 2, 0, (unsigned char*)"Cont:" );
        display_GB2312_string( 2, 50, buff );
       
        //信号强度
        CC1101_Read_Multi_Reg( CC1101_RXFIFO, status, 2 );
        display_GB2312_string( 4, 0, (unsigned char*)"RSSI:" );
        print_char( 4, 50, CC1101_Read_Status( CC1101_RSSI ));
        
        //个数
        CC1101_Read_Multi_Reg( CC1101_RXFIFO, status, 2 );
        display_GB2312_string( 6, 0, (unsigned char*)"Count:" );
        print_byte( 6, 50, ++count);

        CC1101_Clear_RxBuffer;
        delay_ms( 300 );
        CC1101_Rx_Mode;
    }
#endif
}
